#include "deviceserialportcontrol.h"
#include "ui_deviceserialportcontrol.h"
#include<QMessageBox>
Q_GLOBAL_STATIC(DeviceSerialportControl,theInstance);
 int DeviceSerialportControl:: reconnectAttempts=0;

DeviceSerialportControl::DeviceSerialportControl(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::DeviceSerialportControl)
{
    ui->setupUi(this);
    set_Timer();
    initModbusDevice();
    triggerReconnection(isconnectDevice());
    connect(this,&DeviceSerialportControl::reConnectDeviceSignal,this,&DeviceSerialportControl::reConnectDevice);
    //QTimerReadModsimData();

}

DeviceSerialportControl::~DeviceSerialportControl()
{
    delete ui;
}

DeviceSerialportControl *DeviceSerialportControl::instance()
{
    return theInstance;
}

void DeviceSerialportControl::initModbusDevice()
{


    // 先判断modbusDevice是否连接
    if (modbusDevice)
    {
        modbusDevice->disconnectDevice();
        delete modbusDevice;
    }

    // 1. 创建Modbus RTU主站设备
    modbusDevice = new QModbusRtuSerialMaster(this);
    // 2. 配置串口参数（需与ModSim完全一致）
    portName = "COM4"; // 修改为实际串口号（如COM2、/dev/ttyUSB0)
    modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter, portName);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, QSerialPort::Baud9600);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, QSerialPort::Data8);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter, QSerialPort::NoParity);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, QSerialPort::OneStop);



}

bool DeviceSerialportControl::isconnectDevice()
{


    if (!modbusDevice->connectDevice()) {
        qDebug() << "连接失败：" << modbusDevice->errorString();
        qDebug() << "可能原因：串口被占用、权限不足或参数错误";

        QCoreApplication::exit(-1);




        return false;
    }

    qDebug() << "成功连接到串口" << portName<<"左旭驰------->";

    return true;
}

void DeviceSerialportControl::disConnectDevice()
{
    if (modbusDevice)//断联设备
    {
        modbusDevice->disconnectDevice();
//      delete modbusDevice;


    }


}

bool DeviceSerialportControl::triggerReconnection(bool ok)
{
    if(!ok)
    {
//    connectStatus=false;
    if(reconnectAttempts<=maximumReconnectAttempts)
    {
         emit reConnectDeviceSignal();
         reconnectAttempts++;
         return true;
    }
return false;
}
}
bool DeviceSerialportControl::reConnectDevice()
{

    initModbusDevice();
    if(!triggerReconnection(isconnectDevice()))return true;
    return false;

}

void DeviceSerialportControl::onReadFinishCoil()
{

readCoil(modbusDevice);

}

bool DeviceSerialportControl::setDeviceStatusLEDONorOff(int address, bool status, bool MainSwitch)
{

    if(!MainSwitch)//总开关控制
    {
        if(!status){
            writeCoil(modbusDevice,address,9,status);
        }
        else{

            writeCoil(modbusDevice,address,1,status);
        }
        qDebug()<<"-----------------1-------------------"<<endl;

    }
    else
    {
        writeCoil(modbusDevice,address,1,status);
        qDebug()<<"-----------------2-------------------"<<endl;

    }


}
bool DeviceSerialportControl::writeCoil(QModbusRtuSerialMaster *modbusDevice,int address,int number,bool status)
{
    bool flag=false;

    // 创建请求：地址10001对应寄存器地址0，值true（0xFF00）
    QModbusDataUnit request(QModbusDataUnit::Coils, address, number); // 地址0，数量1
    //    for(int i=0;i<number;i++)
    //    {
    //        request.setValue(address,status);
    //        qDebug()<<"第"<<address<<"置位为----->"<<status<<endl;
    //    }
    if(number>=1)
    {
        for(int i=0;i<number;i++)
        {
            request.setValue(i,status);
            if(i==8)
            {
                request.setValue(i,true);
            }
        }
        qDebug()<<"for(-------------------------)";
    }
    else
    {
        switch(address)
        {
        case 0 :
            request.setValue(0,status);
            break;
        case 1 :
            request.setValue(1,status);
            break;
        case 2 :
            request.setValue(2,status);
            break;
        case 3 :
            request.setValue(3,status);
            break;
        case 4 :
            request.setValue(4,status);
            break;
        case 5 :
            request.setValue(5,status);
            break;
        case 6 :
            request.setValue(6,status);
            break;
        case 7 :
            request.setValue(7,status);
            break;
        case 8 :
            request.setValue(8,status);
            break;
        case 9 :
            request.setValue(9,status);
            break;
          }

 }





        //    request.setValue(0,true);
        //    request.setValue(1,true);
        //    request.setValue(2,true);
        //    request.setValue(3,true);
        //    request.setValue(4,true);
        //    request.setValue(5,true);
        //    request.setValue(6,true);
        //    request.setValue(7,true);
        //    request.setValue(8,true);
        //    request.setValue(address, true); // 设置线圈状态

        // 发送请求到设备1
        QModbusReply* reply = modbusDevice->sendWriteRequest(request, 2);
        if (!reply)
        {
            qDebug() << "请求发送失败";
            QMessageBox::information(this,"faild","请求发送失败！");
            return flag;


        }

        // 处理响应
        connect(reply, &QModbusReply::finished, [reply,&flag,this]()
        {
            if (reply->error() == QModbusDevice::NoError)
            {
                qDebug() << "写入成功！";
                if(!getCurrentAutoControl())
                    QMessageBox::information(this,"success","写入成功！");


                flag=true;

            } else
            {
                qDebug() << "错误：" << reply->errorString();
                QMessageBox::information(this,"faild","失败！");

            }
            reply->deleteLater();
        });

        return flag;
}

bool DeviceSerialportControl::readCoil(QModbusRtuSerialMaster *modbusDevice)
{
     bool flag=false;
    // 创建请求：地址0，数量9
        QModbusDataUnit request(QModbusDataUnit::Coils, 0, 10);

        // 发送请求到设备1
        QModbusReply* reply = modbusDevice->sendReadRequest(request, 2);
        if (!reply) {
            qDebug() << "请求发送失败";
            return flag;
        }
        extern deviceStatusDataBlock DeviceStatusDataBlock;
        extern bool MainSwitch;
        // 处理响应
        connect(reply, &QModbusReply::finished, [reply,&flag,this]() {
            if (reply->error() == QModbusDevice::NoError)
            {
                const QModbusDataUnit data = reply->result();

                if(data.value(9))
                {

                    for (int i = 0; i < data.valueCount(); ++i)
                    {
                        qDebug() << "地址" << (10001 + i) << "状态：" << data.value(i);
                        //更新设备状态
                       switch(i)
                       {

                       case 0:
                       {    bool temp=DeviceStatusDataBlock.mainSwitch_LED;//0是主控开关
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.mainSwitch_LED=data.value(i);
                               emit mainSwitch_LEDChanged(0,data.value(i));
                           }


                       }
                           break;
                       case 1:

                       {    bool temp=DeviceStatusDataBlock.IrrigationEquipment_LED;
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.IrrigationEquipment_LED=data.value(i);
                               emit IrrigationEquipment_LEDChanged(1,data.value(i));
                           }


                       }
                           break;
                       case 2:


                       {
                           bool temp=DeviceStatusDataBlock.ventilatingEquipment_LED;//通风设备
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.ventilatingEquipment_LED=data.value(i);
                               emit ventilatingEquipment_LEDChanged(2,data.value(i));
                           }


                       }
                           break;
                       case 3:

                       {
                           bool temp=DeviceStatusDataBlock.CO2Interpolator_LED;//CO2
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.CO2Interpolator_LED=data.value(i);
                               emit CO2Interpolator_LEDChanged(3,data.value(i));
                           }


                       }
                           break;
                       case 4:

                       {
                           bool temp=DeviceStatusDataBlock.rollUpDoor_LED;//卷帘机
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.rollUpDoor_LED=data.value(i);
                               emit rollUpDoor_LEDChanged(4,data.value(i));
                           }


                       }
                           break;
                       case 5:

                       {
                           bool temp=DeviceStatusDataBlock.lightingEquipment_LED;//dengguang
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.lightingEquipment_LED=data.value(i);
                               emit lightingEquipment_LEDChanged(5,data.value(i));
                           }


                       }
                           break;
                       case 6:
                       {
                           bool temp=DeviceStatusDataBlock.heatingEquipment_LED;//dengguang
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.heatingEquipment_LED=data.value(i);
                               emit heatingEquipment_LEDChanged(6,data.value(i));
                           }


                       }
                           break;
                       case 7:
                       {
                           bool temp=DeviceStatusDataBlock.airCooler_LED;//dengguang
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.airCooler_LED=data.value(i);
                               emit airCooler_LEDChanged(7,data.value(i));
                           }


                       }

                           break;
                       case 8:
                       {
                           bool temp=DeviceStatusDataBlock.warningLed;//dengguang
                           if(temp!=data.value(i))
                           {
                               DeviceStatusDataBlock.warningLed=data.value(i);
                               emit warningLedChanged(8,data.value(i));
                           }


                       }
                           break;

                       }


                   }






                }

                flag=true;

            }
            else
            {
                qDebug() << "错误：" << reply->errorString();

            }
            reply->deleteLater();

        });

        return flag;
}

bool DeviceSerialportControl::getCurrentAutoControl()
{
    extern bool AutoControlStatus3;//全局自动开关状态
    return AutoControlStatus3;
}

void DeviceSerialportControl::set_Timer()
{
   m_timer = new QTimer(this);
}

void DeviceSerialportControl::QTimerReadModsimData(bool modsimDeviceSwitch)
{

    if(modsimDeviceSwitch)
    {
        // 启动定时轮询（首次立即执行，后续每1秒一次）
//        QTimer::singleShot(0, this, &DeviceSerialportControl::onReadFinishCoil);
//        QMetaObject::invokeMethod(this, "onReadFinishCoil", Qt::QueuedConnection);


        connect(m_timer, &QTimer::timeout, this, &DeviceSerialportControl::onReadFinishCoil);
        m_timer->start(1000); // 1秒间隔
        if (!m_timer->isActive())
        {
            m_timer->start(1000);
        }


    }
    else
    {

        if (m_timer->isActive())
        {
            m_timer->stop();//关闭定时器
        }



    }






}






















